var feedListData;

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&#]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    var ret = "";
    if (results == null) {
    	results = regex.exec(window.location.hash);
    }
    if (results != null) {
    	ret = decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    
    return ret;
}

function readFeed(wrapperSelector, itemWrapperFormat, dataFields, callback,id) {
	var itemId = id ||getParameterByName("id");
	var item, deferred;
	
	 if (itemId) {
		 deferred = getFeed(itemId);
		 deferred.done(function(item) {
			 deleteFromFeedListData(itemId);
	 		populateElement([item], wrapperSelector, itemWrapperFormat, dataFields, callback);
		 });
	 }
	 
	 return deferred;
}

function saveFeed(itemId, callback) {
	var requestdeferred = getFeed(itemId);
	var retDeferred = new $.Deferred();
	requestdeferred.done(function(item) {
		SavedFeeds.insert(item, function saveSucceed() {
			deleteFromFeedListData(itemId);
			retDeferred.resolve(item);
		}, function saveFailed() {
			retDeferred.reject(item);
		});
	}).fail(function(date) {
		retDeferred.reject(item);
	});
		
	return retDeferred;
}
function findIndex(arr, itemId) {
	var currentIndex = 0;
	
	for (currentIndex = 0; currentIndex < arr.length; ++currentIndex) {
		if ($(arr[currentIndex]).attr("id") == itemId) {
			break;
		}
	}
	
	return currentIndex;
}
function deleteFromFeedListData(itemId)
{
	if(feedListData) {
		item = $(feedListData).find("item[id=" + itemId + "]"); // get item from global var
		var orginalFeedsLength = feedListData.length || $(feedListData).find("item").length;
		var currentLength = orginalFeedsLength;
		if (item && item.length > 0) {
			$(item).remove();
			currentLength = feedListData.length || $(feedListData).find("item").length;
			if (orginalFeedsLength == currentLength) {
				$(feedListData).remove(item); // remove harder
			}
		} else {
			var itemIndex = findIndex(feedListData, itemId);
			if(itemIndex >= 0)
			{
				feedListData.splice(itemIndex,1);
			}
		}
	}
}

function populateContent(feed, wrapperSelector, itemWrapperFormat, tableName, dataFields, callback) {
    populateElement(feed, wrapperSelector, itemWrapperFormat, dataFields, callback);
}

function itemHas(item, propertyName) {
    return $(item).children(propertyName).length > 0;
}
function itemGet(item, propertyName) {
    var returnValue = "";

    if (itemHas(item, propertyName)) {
        returnValue = $(item).children(propertyName)[0].textContent;
    }

    return returnValue;
}

function initLoginPageComponenets() {
	$(document).on("click","#login-button",function() {
		login();
	});
	$("#login-cancel").click(function() {
		$("#login-error").text(""); // clears login error
	});
}

function tryLogin(username, password) {
    username = username || $("#login-username").val();
    password = password || $("#login-password").val();
    var emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
    var requestDeferred, retDeferred = new $.Deferred();
    var params;
    $("#login-error").text("").removeClass();

    if (!username || !password) {
        $("#login-error").text("Invalid username/password").addClass("alert alert-error");
        retDeferred.reject();
    }

    if (!emailRegex.test(username.toUpperCase())) {
        $("#login-error").text("Invalid mail format").addClass("alert alert-error");
        retDeferred.reject();
    }

    if (retDeferred.state() != "rejected") {
	    params = "call=login&username=" + username + "&password=" + password;
	    requestDeferred = sendRequest("../ApiUser", params, "POST");
	    requestDeferred.always(function(response) {
	    	response = $.parseJSON(response);
	    	if (response && response.status) {
	    		setUser(username);
	    		$("#login-username").val("");
	    		$("#login-password").val("");
	    		retDeferred.resolve(response);
	    	} else {
	    		var message = "Login error";
	    		if (response && response.msg) {
	    			message = response.msg;
	    		}
	    		retDeferred.reject(response);
	            $("#login-error").text(message).addClass("alert alert-error");
	    	}
	    });
    }
    
    return retDeferred;
}
function setUser(user)
{
	localStorage.setItem("user", user);
}
function getUser()
{
	return localStorage.getItem("user");
}
function clearUser() {
	setUser(null);
}

function isLoggedIn() {
	var userId = getUser();
	return (userId && typeof(userId) != "null");
}

function initSignPageComponenets() {
	$(document).on("click","#signup-button",function() {
		trySignUp();
		
	});
	$("#login-cancel").click(function() {
		$("#login-error").text(""); // clears login error
	});
}

function trySignUp() {
	var firstname = $("#signup-fname").val();
	var lastname = $("#signup-lname").val();
    var username = $("#signup-email").val();
    var password = $("#signup-password").val();
    var confirmpassword = $("#signup-confirm-password").val();
    
    var emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
    var requestDeferred, retDeferred = new $.Deferred();
    var params;
    $("#signup-login-error").text("").removeClass();

    if (!username || !password) {
        $("#signup-login-error").text("Invalid username/password").addClass("alert alert-error");
        retDeferred.reject();
    }
    else if (!firstname || !lastname) {
        $("#signup-login-error").text("first name or last name are empty").addClass("alert alert-error");
        retDeferred.reject();
    }
    else if (confirmpassword != password) {
        $("#signup-login-error").text("confirm password and password are not the same ").addClass("alert alert-error");
        retDeferred.reject();
    }
    else if (!emailRegex.test(username.toUpperCase())) {
        $("#signup-login-error").text("Invalid mail format").addClass("alert alert-error");
        retDeferred.reject();
    }

    if (retDeferred.state() != "rejected") {
	    params = "call=new&mail=" + username + "&password=" + password +"&firstName="+firstname+"&lastName="+lastname;
	    requestDeferred = sendRequest("../ApiUser", params, "POST");
	    requestDeferred.always(function(response) {
	    	response = $.parseJSON(response);
	    	if (response && response.status) {
	    		retDeferred.resolve(response);
	    		login(username,password);
	    	} else {
	    		var message = "signup error";
	    		if (response && response.msg) {
	    			message = response.msg;
	    		}
	    		retDeferred.reject(response);
	            $("#signup-login-error").text(message).addClass("alert alert-error");
	    	}
	    });
    }
    
    return retDeferred;
}

function sendRequest(url, params, method) {
	showLoader("Please wait");
	method = method || "GET";
	return $.ajax({
		url: url,
		type: method,
		data: params
	}).always(function(){
		hideLoader();
	});
}

//function initSavedFeeds(data){
//	var deferred = new $.Deferred();
//	var counter = 0;
//	if (data && data.length) {
//		for (var i = 0; i < data.length ; ++i) {
//			var item = data[i];
//			SavedFeeds.insert(item, function saveSucceed() {
//				counter++;
//				if (counter == data.length) {
//					deferred.resolve();
//				}
//			}, function saveFailed() {
//				counter++;
//				if (counter == data.length) {
//					deferred.resolve();
//				}
//			});
//		}
//	}
//	else {
//		deferred.resolve();
//	}
//	
//	return deferred;
//}

function requestSavedFeeds() {
	//return getFeeds("1");
}

function getFeeds(cachedState) {
	cachedState = cachedState || "0";
	params = "call=getAllItems&cache=" + cachedState;
	var retDeferred = new $.Deferred();
	//var requestDeferred = sendRequest("../ApiUser", params);
	var requestDeferred = sendRequest("../shared/xml/tempDataChannel4.xml", params); // for debug
	requestDeferred.done(function(response) {
		try {
			if (response.nodeName == "#document") {
				feedListData = $(response).find("item");
				retDeferred.resolve(feedListData);
			} else {
				var obj = $.parseJSON(response);
				if (obj && obj.status) {
					feedListData = obj.data;
					retDeferred.resolve(obj.data);
				}
				else {
					retDeferred.reject(response);
				}
			}
		}
		catch (ex) {
			retDeferred.reject(response);
		}
	}).fail(function(response) {
		retDeferred.reject(response);
	});
	
	return retDeferred;
}

function populateElement(items, wrapperSelector, itemWrapperFormat, dataFields, callback) {
    var holder = $(wrapperSelector),    // find wrapper
        fields = dataFields.split(","), // get array of requested fields
        values = [],
        itemHolder,
        i, j;
   
    holder.empty();    
    for (i = 0; i < items.length; ++i) 
	{
    	for (j = 0; j < fields.length; ++j) {
    		values[j] = $(items[i]).attr(fields[j]) || $(items[i]).find(fields[j]).text();
    	}
             
        // call format.apply so the values will be passed as multiple arguments and not as an 1 array argument
        itemHolder = $(itemWrapperFormat.format.apply(itemWrapperFormat, values)); // create holder template
        holder.append(itemHolder);
    }
    
    if (typeof (callback) == "function") {
        callback();
    }
}

function getFeed(feedId)
{
	var item, requestDeferred, retDeferred = new $.Deferred();
	
	 if (feedId) {
		 if (typeof(feedListData) != 'undefined' && feedListData) {
			// if we have global item 
			item = $(feedListData).find("item[id=" + feedId + "]").get(0); // get item from global var
			
			if (!item) {
				item = $.grep(feedListData, function(feed) {
					return $(feed).attr("id") ==  feedId;
				})
			}
		 }
		 
		if (item) {
			retDeferred.resolve(item); 
		}
		else
			{
			SavedFeeds.getById(feedId,function(tx,result){
				if(result.rows && result.rows.length>0)
					{
						item=result.rows.item(0);
						retDeferred.resolve(item); 
					}
				requestDeferred = sendRequest("../shared/xml/oneItemXmlFile.xml");
				requestDeferred.done(function (data) {
					var xmlDoc = data;
			 		
			 		if (!item) {
			 			// if item was not found in the global var earlier then get it from the server response
			 			item = xmlDoc.getElementsByTagName("item");
			 		}
					
			 		if (retDeferred.state() === "pending") {
			 			retDeferred.resolve(item);
			 		}
				}).fail(function(error) {
					retDeferred.reject(error);
				});
			});
			}
		
	
	 }
	 
	 return retDeferred;
}

function requestSavedFeeds()
{
	var deferred = new $.Deferred();
	SavedFeeds.get(function(transaction, result) {
		var items = [];
		var i;
		for (i=0; i < result.rows.length; i++) {
			items.push(result.rows.item(i));
		}
		
		deferred.resolve(items);
	}, function (transaction, error) {
		deferred.reject(error);
	});
	
	return deferred;
}
function requsetFeedsFromServer()
{ 
	params = "call=getFeeds";
	var deferred= sendRequest("../ApiUser", params, "POST");
	deferred.done(function(data) {
		feedListData = data;
	});
	
	return deferred;
}
function requsetLogOutServer()
{
	params = "call=logout";
	var requestdeferred = sendRequest("../ApiUser", params, "POST");
	var retDeferred = new $.Deferred();
	
	requestdeferred.done(function(response) {
		SavedFeeds.clear(function clearTable() {
			clearUser();
			retDeferred.resolve(response);
		}, function clearFailed() {
			retDeferred.reject(response);
		});
	}).fail(function(date) {
		retDeferred.reject(response);
	});
		
	return retDeferred;
}

function addUnreadProperty()
{
	var data=$(feedListData).find("item");
	
	if(data.length == 0)
		{
		 	data=feedListData;
		}
	for(var i=0;i<data.length;i++)
		{
			data[i].attr("read",false);
		}
}

function addFeedToServer() {
	var feedName = $("#rss-name").val();
    var feedUrl = $("#rss-url").val();
    var requestDeferred, retDeferred = new $.Deferred();
    var params;
    $("#add-feed-alert").text("").removeClass();

    if (!feedName || !feedUrl) {
    	setAddFeedAlert("All fields are required", "error");
        retDeferred.reject({ msg: "All fields are required" });
    }

    if (retDeferred.state() != "rejected") {
	    params = "call=new&name=" + feedName + "&url=" + feedUrl;
	    requestDeferred = sendRequest("../ApiRssFeed", params, "POST");
	    requestDeferred.always(function(response) {
	    	response = $.parseJSON(response);
	    	if (response && response.status) {
	    		retDeferred.resolve(response);
	    	} else {
	    		var message = "Error adding feed";
	    		if (response && response.msg) {
	    			message = response.msg;
	    		}
	    		retDeferred.reject(response);
	        	setAddFeedAlert(message, "error");
	            $("#add-feed-alert").text(message).addClass("alert alert-error");
	    	}
	    });
    }
    
    return retDeferred;
}

function setAddFeedAlert(message, cssClass) {
	$("#new-feed-form-message").html(message).removeClass().addClass("alert alert-" + cssClass);
}



